﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsPlatform.PermissionManagement.IPermissionManagement;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Query.PermissionManagement.UserInfo;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Query.PermissionManagement.BaseQuery;
using SportsPlatform.Dto.PermissionManagement.UserInfo;
using SportsPlatform.Dto.PermissionManagement.CompanyInfo;
using SportsPlatform.Dto.PermissionManagement.RoleInfo;
using SportsPlatform.Dto.PermissionManagement.DepartmentInfo;
using Abp.Domain.Repositories;
using SportsPlatform.Jwt;
using Abp.Application.Services;
using Abp.Collections.Extensions;
using SportsPlatform.Dto.PermissionManagement.PlatformInfo;
using SportsPlatform.Dto.SportBusiness.Employee;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;
using SportsPlatform.Authorization.Users;
using SportsPlatform.Redis;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using Polly.Caching;
using SportsPlatform.Helpers;

namespace SportsPlatform.PermissionManagement.PermissionManagement
{
    /// <summary>
    /// 用户信息表
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class UserInfoService : SportsPlatformAppServiceBase, IUserInfoService
    {
        private readonly IRepository<UserInfo, Guid> _userinfoRepository;

        private readonly IRepository<CompanyInfo, Guid> _companyinfoRepository;

        private readonly IRepository<AuthorizationInfo, Guid> _authorizationRepository;

        private readonly IRepository<RoleInfo, Guid> _roleinfoRepository;

        private readonly IRepository<PlatformInfo, Guid> _platforminfoRepository;

        private readonly IRepository<DepartmentInfo, Guid> _departmentinfoRepository;

        private readonly IRepository<RoleFunction, Guid> _roleFunctionRepository;

        private readonly IRepository<FunctionInfo, Guid> _functionInfoRepository;

        private readonly IRedisRepository _redisRepository;
        private readonly IHttpContextAccessor _context;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="userinfoRepository"></param>
        /// <param name="companyinfoRepository"></param>
        /// <param name="roleinfoRepository"></param>
        /// <param name="departmentinfoRepository"></param>
        /// <param name="platforminfoRepository"></param>
        /// <param name="roleFunctionRepository"></param>
        /// <param name="functionInfoRepository"></param>
        /// <param name="authorizationRepository"></param>
        public UserInfoService(IRepository<UserInfo, Guid> userinfoRepository, IRepository<CompanyInfo, Guid> companyinfoRepository,
            IRepository<RoleInfo, Guid> roleinfoRepository, IRepository<DepartmentInfo, Guid> departmentinfoRepository,
            IRepository<PlatformInfo, Guid> platforminfoRepository, IRepository<RoleFunction, Guid> roleFunctionRepository,
            IRepository<FunctionInfo, Guid> functionInfoRepository, IRepository<AuthorizationInfo, Guid> authorizationRepository,
            IHttpContextAccessor context, IRedisRepository redisRepository) : base(context)
        {
            _userinfoRepository = userinfoRepository;
            _companyinfoRepository = companyinfoRepository;
            _roleinfoRepository = roleinfoRepository;
            _departmentinfoRepository = departmentinfoRepository;
            _platforminfoRepository = platforminfoRepository;
            _roleFunctionRepository = roleFunctionRepository;
            _functionInfoRepository = functionInfoRepository;
            _authorizationRepository = authorizationRepository;
            _redisRepository = redisRepository;
            _context = context;

        }
        /// <summary>
        /// 新增一个用户信息
        /// </summary>
        /// <param name="addUserInfoQuery"></param>
        /// <returns></returns>
        public async Task<ResultByIdDto> AddUserInfo(AddUserInfoQuery addUserInfoQuery)
        {
            ResultByIdDto result = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                UserInfo userInfo = ObjectMapper.Map<UserInfo>(addUserInfoQuery);
                userInfo.CreateTime = DateTime.Now;
                userInfo.CreateUserId = token.Id;
                userInfo.PlatformId = _userinfoRepository.FirstOrDefault(info => info.Id == token.Id).PlatformId;
                if (string.IsNullOrEmpty(userInfo.PassWord))
                {
                    userInfo.PassWord = CommonHelper.MD5Encryption("a123456", 32);//如果没传密码，默认为a123456
                }
                if ((await _userinfoRepository.FirstOrDefaultAsync(info => (info.LoginName == userInfo.LoginName || info.UserTel == userInfo.UserTel) && info.IsDeleted == false)) != null)
                {
                    result.IsSuccess = false;
                    result.Code = HttpResultCode.Fail;
                    result.Message = "登录名或手机号码有重复！";
                    return result;
                }
                var userid = await _userinfoRepository.InsertAndGetIdAsync(userInfo);
                if (userid != Guid.Empty)
                {
                    result.IsSuccess = true;
                    result.Code = HttpResultCode.Success;
                    result.Message = "新增成功！";
                    result.Data = new() { Id = userid };
                }
                else
                {
                    result.IsSuccess = false;
                    result.Code = HttpResultCode.SqlError;
                    result.Message = "执行sql失败！";
                }
            }
            catch (Exception e)
            {
                result.IsSuccess = false;
                result.Code = HttpResultCode.Error;
                result.Message = e.Message.ToString();
            }
            return result;
        }

        /// <summary>
        /// 登录获取信息
        /// </summary>
        /// <param name="getLoginUserInfoQuery"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetLoginUserInfoDto>> GetLoginUserInfo(GetLoginUserInfoQuery getLoginUserInfoQuery)
        {
            ResultDto<GetLoginUserInfoDto> resultDto = new();
            try
            {
                //判断用户名是否为空
                if (string.IsNullOrEmpty(getLoginUserInfoQuery.LoginName))
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.Message = "用户名不能为空！";
                    return resultDto;
                }
                //密码为空则只判断是否存在账户名
                if (string.IsNullOrEmpty(getLoginUserInfoQuery.PassWord))
                {
                    var userinfo = await _userinfoRepository.FirstOrDefaultAsync(info => info.LoginName == getLoginUserInfoQuery.LoginName && info.IsDeleted == false);
                    if (userinfo == null)
                    {
                        resultDto.IsSuccess = true;
                        resultDto.Code = HttpResultCode.Success;
                        resultDto.Message = "用户名可以使用！";
                        return resultDto;
                    }
                    else
                    {
                        resultDto.IsSuccess = false;
                        resultDto.Code = HttpResultCode.Fail;
                        resultDto.Message = "用户名已存在";
                        return resultDto;
                    }
                }
                else
                {
                    var userinfo = await _userinfoRepository.FirstOrDefaultAsync(info => info.LoginName == getLoginUserInfoQuery.LoginName && info.PassWord == getLoginUserInfoQuery.PassWord);
                    if (userinfo == null)
                    {
                        resultDto.IsSuccess = false;
                        resultDto.Code = HttpResultCode.SqlError;
                        resultDto.Message = "用户名或密码错误！";
                        return resultDto;
                    }
                    else
                    {
                        if (userinfo.States == false || userinfo.IsDeleted == true)
                        {
                            resultDto.IsSuccess = false;
                            resultDto.Code = HttpResultCode.NoPermission;
                            resultDto.Message = "该用户被删除或者被禁用！请联系管理员！";
                            return resultDto;
                        }
                        GetLoginUserInfoDto userinfodto = ObjectMapper.Map<GetLoginUserInfoDto>(userinfo);
                        resultDto.IsSuccess = true;
                        resultDto.Code = HttpResultCode.Success;
                        resultDto.Message = "登录成功！";
                        //公司Id不为空，返回公司信息
                        if (userinfo.CompanyId != null)
                        {
                            CompanyInfo companyinfo = await _companyinfoRepository.FirstOrDefaultAsync(info => info.Id == userinfo.CompanyId && info.IsDeleted == false && info.States == true && info.AuthorizeEndTIme > DateTime.Now);
                            if (companyinfo != null)
                            {
                                //获取授权信息 暂未启用
                                //AuthorizationInfo authorizationInfo = await _authorizationRepository.FirstOrDefaultAsync(info => info.CompanyId == companyinfo.Id && info.UserId == userinfo.Id && info.States == 1 && info.IsDeleted == false);
                                //if (authorizationInfo != null)
                                //{
                                //    userinfodto.CompanyInfo = ObjectMapper.Map<GetCompanyInfoDto>(companyinfo);
                                //}
                                //else
                                //{
                                //    resultDto.IsSuccess = false;
                                //    resultDto.Code = HttpResultCode.NoPermission;
                                //    resultDto.Message = "账户授权审核未通过无法登录！";
                                //    return resultDto;
                                //}
                                userinfodto.CompanyInfo = ObjectMapper.Map<GetCompanyInfoDto>(companyinfo);
                            }
                            else
                            {
                                resultDto.IsSuccess = false;
                                resultDto.Code = HttpResultCode.NoPermission;
                                resultDto.Message = "该商户授权结束无法登录！";
                                return resultDto;
                            }
                        }
                        //角色信息不为空，返回角色信息
                        if (userinfo.RoleId != null)
                        {
                            RoleInfo roleinfo = await _roleinfoRepository.FirstOrDefaultAsync(info => info.Id == userinfo.RoleId);
                            if (roleinfo != null)
                            {
                                userinfodto.RoleInfo = ObjectMapper.Map<GetRoleInfoDto>(roleinfo);
                            }
                        }
                        //返回权限功能
                        if (userinfo.IsAllPermission == true)//管理员拥有所有权限
                        {
                            userinfodto.Childrens = GetFunctionInfoTreeList(Guid.Empty, Guid.Empty).OrderBy(info => info.FunctionNo).ToList();
                        }
                        else if (userinfo.RoleId != null && userinfo.RoleId != Guid.Empty)//有角色Id获取对应角色Id权限
                        {
                            userinfodto.Childrens = GetFunctionInfoTreeList(Guid.Empty, (Guid)userinfo.RoleId).OrderBy(info => info.FunctionNo).ToList();
                        }
                        else//没有权限
                        {
                            userinfodto.Childrens = null;
                        }
                        //部门信息不为空，返回部分信息
                        if (userinfo.DepartmentId != null)
                        {
                            DepartmentInfo departmentInfo = await _departmentinfoRepository.FirstOrDefaultAsync(info => info.Id == userinfo.DepartmentId);
                            if (departmentInfo != null)
                            {
                                userinfodto.DepartmentInfo = ObjectMapper.Map<GetDepartmentInfoDto>(departmentInfo);
                            }
                        }

                        if (userinfo.PlatformId != null)
                        {
                            PlatformInfo platformInfo = await _platforminfoRepository.FirstOrDefaultAsync(info => info.Id == userinfo.PlatformId);
                            if (platformInfo != null)
                            {
                                userinfodto.PlatformInfo = ObjectMapper.Map<GetPlatformInfoDto>(platformInfo);
                            }
                        }
                        //返回ToKen

                        var tokenKey = UldAdminGlobalContext.SystemConfig.TokenKey;
                        var tokenExpiration = UldAdminGlobalContext.SystemConfig.UserTokenExpiration;
                        var limitCount = UldAdminGlobalContext.SystemConfig.LogonCountLimit;
                        var token = String.Format(tokenKey, userinfo.Id, Guid.NewGuid());
                        userinfodto.Token = token;
                        if (!getLoginUserInfoQuery.IsClient)
                        {
                            //pc端token过期时间为1小时
                            userinfodto.TokenExpiration = tokenExpiration * 60;
                            //初始化用户口令
                            await this._redisRepository.SetAsync(userinfodto.Token, userinfo, userinfodto.TokenExpiration);
                        }
                        else
                        {
                            //客户端token过期时间为5小时
                            userinfodto.TokenExpiration = tokenExpiration * 300;
                            //初始化用户口令
                            await this._redisRepository.SetAsync(userinfodto.Token, userinfo, userinfodto.TokenExpiration);
                        }


                        TokenModelJwt jwtmodel = new TokenModelJwt();
                        jwtmodel.Uid = userinfo.Id;
                        jwtmodel.CompanyId = userinfo.CompanyId;
                        resultDto.Data = userinfodto;
                        //更新登录时间
                        try
                        {
                            userinfo.LoginTime = DateTime.Now;
                            await _userinfoRepository.UpdateAsync(userinfo);
                        }
                        catch { }
                    }
                }
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }
        /// <summary>
        /// 获取角色对应功能列表
        /// </summary>
        /// <returns></returns>
        public async Task<ResultListDto<FunctionChildren>> GetFunctionChildren()
        {
            ResultListDto<FunctionChildren> resultListDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                //返回权限功能
                if (token.IsAllPermission == true)//管理员拥有所有权限
                {
                    resultListDto.IsSuccess = true;
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Data = GetFunctionInfoTreeList(Guid.Empty, Guid.Empty).OrderBy(info => info.FunctionNo).ToList();
                }
                else if (token.RoleId != null && token.RoleId != Guid.Empty)//有角色Id获取对应角色Id权限
                {
                    resultListDto.IsSuccess = true;
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Data = GetFunctionInfoTreeList(Guid.Empty, (Guid)token.RoleId).OrderBy(info => info.FunctionNo).ToList();
                }
                else//没有权限
                {
                    resultListDto.IsSuccess = false;
                    resultListDto.Code = HttpResultCode.NotData;
                    resultListDto.Message = "没有权限";
                }

            }
            catch (Exception e)
            {
                resultListDto.IsSuccess = false;
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }

        /// <summary>
        /// 递归获取树型菜单
        /// </summary>
        /// <param name="ParentId"></param>
        /// <param name="RoleId"></param>
        /// <returns></returns>
        public List<FunctionChildren> GetFunctionInfoTreeList(Guid ParentId, Guid RoleId)
        {
            List<FunctionChildren> resultListDto = new();
            try
            {
                var functioninfolist = _functionInfoRepository.GetAllList(info => info.ParentId == ParentId && info.States == true && info.IsDeleted == false);
                if (functioninfolist != null && functioninfolist.Count > 0)
                {
                    foreach (FunctionInfo item in functioninfolist)
                    {
                        if (RoleId == Guid.Empty || item.FunctionIsAvailable != true)
                        {
                            var treelist = GetFunctionInfoTreeList(item.Id, RoleId);
                            if (RoleId == Guid.Empty || (treelist != null && treelist.Count > 0))
                            {
                                FunctionChildren children = new FunctionChildren();
                                children.Path = item.Path;
                                children.Name = item.PcName;
                                children.Component = string.IsNullOrEmpty(item.Component) ? null : item.Component;
                                children.Redirect = string.IsNullOrEmpty(item.Redirect) ? null : item.Redirect;
                                children.FunctionNo = item.FunctionNo;
                                children.Meta = new() { Icon = item.Icon, Title = item.FunctionName, IsLink = item.IsLink, IsHide = item.IsHide, IsFull = item.IsFull, IsAffix = item.IsAffix, IsKeepAlive = item.IsKeepAlive, ActiveMenu = string.IsNullOrEmpty(item.ActiveMenu) ? null : item.ActiveMenu };
                                children.Children = (treelist != null && treelist.Count > 0) ? treelist : null;
                                resultListDto.Add(children);
                            }
                        }
                        else
                        {
                            if (_roleFunctionRepository.FirstOrDefault(info => info.RoleId == RoleId && info.FunctionId == item.Id && info.IsDeleted == false && info.States == true) != null)
                            {
                                FunctionChildren children = new FunctionChildren();
                                children.Path = item.Path;
                                children.Name = item.PcName;
                                children.Component = string.IsNullOrEmpty(item.Component) ? null : item.Component;
                                children.Redirect = string.IsNullOrEmpty(item.Redirect) ? null : item.Redirect;
                                children.FunctionNo = item.FunctionNo;
                                children.Meta = new() { Icon = item.Icon, Title = item.FunctionName, IsLink = item.IsLink, IsHide = item.IsHide, IsFull = item.IsFull, IsAffix = item.IsAffix, IsKeepAlive = item.IsKeepAlive, ActiveMenu = string.IsNullOrEmpty(item.ActiveMenu) ? null : item.ActiveMenu };
                                var treelist = GetFunctionInfoTreeList(item.Id, RoleId);
                                children.Children = (treelist != null && treelist.Count > 0) ? treelist : null;
                                resultListDto.Add(children);
                            }
                        }
                    }
                }
            }
            catch
            {

            }
            return resultListDto;
        }


        /// <summary>
        /// 更改用户密码
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateUserInfoPassWord(UpdateUserInfoPassWordQuery query)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                //判断修改ID是否存在
                UserInfo userinfo = await _userinfoRepository.FirstOrDefaultAsync(info => info.Id == query.Id);
                if (userinfo == null)
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.SqlError;
                    resultDto.Message = "未获取到用户信息！id:" + query.Id;
                    return resultDto;
                }
                else
                {
                    if (userinfo.PassWord.Equals(query.OldPassWord))
                    {
                        //更改密码
                        userinfo.PassWord = query.NewPassWord;
                        userinfo.UpdateUserId = token.Id;
                        userinfo.UpdateTime = DateTime.Now;
                        await _userinfoRepository.UpdateAsync(userinfo);
                        resultDto.IsSuccess = true;
                        resultDto.Code = HttpResultCode.Success;
                        resultDto.Message = "更改成功！";
                    }
                    else
                    {
                        resultDto.IsSuccess = false;
                        resultDto.Code = HttpResultCode.Fail;
                        resultDto.Message = "原密码输入错误！";
                    }
                }
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 根据Id删除用户信息
        /// </summary>
        /// <param name="deleteOrQueryModel"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> DeleteUserInfo(DeleteOrGetModelQuery deleteOrQueryModel)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var userinfo = await _userinfoRepository.FirstOrDefaultAsync(info => info.Id == deleteOrQueryModel.Id);
                if (userinfo != null)
                {
                    userinfo.IsDeleted = true;
                    userinfo.DeleteTime = DateTime.Now;
                    userinfo.DeleteUserId = token.Id;
                    await _userinfoRepository.UpdateAsync(userinfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "删除成功！";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.SqlError;
                    baseResultDto.Message = "未获取到Id信息！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 根据Id获取用户信息
        /// </summary>
        /// <param name="deleteOrQueryModel"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ResultDto<GetUserInfoDto>> GetUserInfo(DeleteOrGetModelQuery deleteOrQueryModel)
        {
            ResultDto<GetUserInfoDto> resultDto = new();
            try
            {
                var userinfo = await _userinfoRepository.FirstOrDefaultAsync(info => info.Id == deleteOrQueryModel.Id);
                if (userinfo != null)
                {
                    resultDto.IsSuccess = true;
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.Message = "查询成功！";
                    resultDto.Data = ObjectMapper.Map<GetUserInfoDto>(userinfo);
                    resultDto.Data.UserDateOfBirth = userinfo.UserDateOfBirth == null ? "" : ((DateTime)userinfo.UserDateOfBirth).ToString("yyyy-MM-dd");
                }
                else
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.SqlError;
                    resultDto.Message = "未获取到Id信息！";
                }
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 筛选模糊查询
        /// </summary>
        /// <param name="getUserInfoQuery"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PagePagingDto<GetUserInfoListPageDto>> GetUserInfoListPage(GetUserInfoListPageQuery getUserInfoQuery)
        {
            PagePagingDto<GetUserInfoListPageDto> pagePagingDto = new();
            try
            {
                //用于判定是平台用户还是客户用户
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                var userinfolist = (await _userinfoRepository.GetAllListAsync(info => info.IsDeleted == false))
                     .WhereIf(!string.IsNullOrEmpty(getUserInfoQuery.UserNaemOrTel), userinfo => userinfo.LoginName.Contains(getUserInfoQuery.UserNaemOrTel) || userinfo.UserName.Contains(getUserInfoQuery.UserNaemOrTel) || userinfo.UserTel.Contains(getUserInfoQuery.UserNaemOrTel))
                     .WhereIf(!string.IsNullOrEmpty(getUserInfoQuery.LastLoginTime), userinfo => userinfo.LoginTime != null && userinfo.LoginTime < Convert.ToDateTime(getUserInfoQuery.LastLoginTime).AddDays(1).AddSeconds(-1))
                     .WhereIf(getUserInfoQuery.RoleId != null, userinfo => userinfo.RoleId == getUserInfoQuery.RoleId)
                     .WhereIf(getUserInfoQuery.States != null, userinfo => userinfo.States == getUserInfoQuery.States)
                     .WhereIf(token.CompanyId != null, userinfo => userinfo.CompanyId == token.CompanyId)
                     .OrderByDescending(info => info.CreateTime)
                     .ToList();
                var userinfopage = userinfolist
                  .Skip((getUserInfoQuery.PageIndex - 1) * getUserInfoQuery.PageSize)
                  .Take(getUserInfoQuery.PageSize)
                 .ToList();
                if (userinfopage != null && userinfopage.Count > 0)
                {
                    pagePagingDto.IsSuccess = true;
                    pagePagingDto.Code = HttpResultCode.Success;
                    pagePagingDto.Message = "查询成功！";
                    pagePagingDto.TotalCount = userinfolist.Count;
                    var userInfoDtos = ObjectMapper.Map<List<GetUserInfoListPageDto>>(userinfopage);
                    var companylist = await _companyinfoRepository.GetAllListAsync();
                    var userlist = await _userinfoRepository.GetAllListAsync();
                    var rolelist = await _roleinfoRepository.GetAllListAsync();
                    var platlist = await _platforminfoRepository.GetAllListAsync();
                    userInfoDtos.ForEach(item =>
                    {
                        var userinfo = userlist.FirstOrDefault(info => info.Id == item.Id);
                        item.CompanyName = userinfo.CompanyId != null ? (companylist.FirstOrDefault(info => info.Id == userinfo.CompanyId).CompanyName) : "";
                        item.CreateUserName = userinfo.CreateUserId != Guid.Empty ? (userlist.FirstOrDefault(info => info.Id == userinfo.CreateUserId).UserName) : "";
                        item.RoleName = userinfo.RoleId != null ? (rolelist.FirstOrDefault(info => info.Id == userinfo.RoleId).RoleName) : "";
                        item.UserTel = $"{item.UserTel.Substring(0, 3)}****{item.UserTel.Substring(item.UserTel.Length - 4, 4)}";
                        item.CreateTime = userinfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                        item.LoginTime = userinfo.LoginTime == null ? "" : ((DateTime)userinfo.LoginTime).ToString("yyyy-MM-dd HH:mm:ss");
                    });
                    pagePagingDto.Data = userInfoDtos;
                }
                else
                {
                    pagePagingDto.IsSuccess = false;
                    pagePagingDto.Code = HttpResultCode.SqlError;
                    pagePagingDto.Message = "未查询到相关用户信息！";
                }
            }
            catch (Exception e)
            {
                pagePagingDto.IsSuccess = false;
                pagePagingDto.Code = HttpResultCode.Error;
                pagePagingDto.Message = e.Message.ToString();
            }
            return pagePagingDto;
        }
        /// <summary>
        /// 是否启用
        /// </summary>
        /// <param name="isStatesModel"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> IsStatesUserInfo(IsStatesdModel isStatesModel)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var userinfo = await _userinfoRepository.FirstOrDefaultAsync(info => info.Id == isStatesModel.Id);
                if (userinfo != null)
                {
                    userinfo.States = isStatesModel.States;
                    userinfo.UpdateTime = DateTime.Now;
                    userinfo.UpdateUserId = token.Id;
                    await _userinfoRepository.UpdateAsync(userinfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "更改成功！";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "没有获取Id相关信息！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }
        /// <summary>
        /// 跟新用户信息表
        /// </summary>
        /// <param name="updateUserInfoQuery"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateUserInfo(UpdateUserInfoQuery updateUserInfoQuery)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                //判断CompanyId是否有效
                if (updateUserInfoQuery.CompanyId != null)
                {
                    if ((await _companyinfoRepository.FirstOrDefaultAsync(info => info.Id == updateUserInfoQuery.CompanyId && info.IsDeleted == false && info.States == true)) == null)
                    {
                        baseResultDto.IsSuccess = false;
                        baseResultDto.Code = HttpResultCode.Fail;
                        baseResultDto.Message = "CompanyId无效!不存在有效的信息！";
                        return baseResultDto;
                    }
                }
                //判断RoleId是否有效
                if (updateUserInfoQuery.RoleId != null)
                {
                    if ((await _roleinfoRepository.FirstOrDefaultAsync(info => info.Id == updateUserInfoQuery.RoleId && info.IsDeleted == false && info.States == true)) == null)
                    {
                        baseResultDto.IsSuccess = false;
                        baseResultDto.Code = HttpResultCode.Fail;
                        baseResultDto.Message = "RoleId无效!不存在有效的信息！";
                        return baseResultDto;
                    }
                }
                //判断登录是否重复
                if (!string.IsNullOrEmpty(updateUserInfoQuery.LoginName))
                {
                    if ((await _userinfoRepository.FirstOrDefaultAsync(info => info.LoginName == updateUserInfoQuery.LoginName && info.Id != updateUserInfoQuery.Id && info.IsDeleted == false)) != null)
                    {
                        baseResultDto.IsSuccess = false;
                        baseResultDto.Code = HttpResultCode.Fail;
                        baseResultDto.Message = "登录名有重复！";
                        return baseResultDto;
                    }
                }
                //判断手机号是否重复
                if (!string.IsNullOrEmpty(updateUserInfoQuery.UserTel))
                {
                    if ((await _userinfoRepository.FirstOrDefaultAsync(info => info.UserTel == updateUserInfoQuery.UserTel && info.Id != updateUserInfoQuery.Id && info.IsDeleted == false)) != null)
                    {
                        baseResultDto.IsSuccess = false;
                        baseResultDto.Code = HttpResultCode.Fail;
                        baseResultDto.Message = "手机号有重复！";
                        return baseResultDto;
                    }
                }
                var userinfo = await _userinfoRepository.FirstOrDefaultAsync(info => info.Id == updateUserInfoQuery.Id);
                if (userinfo != null)
                {
                    if (!string.IsNullOrEmpty(updateUserInfoQuery.UserName))
                    {
                        userinfo.UserName = updateUserInfoQuery.UserName;
                    }
                    if (!string.IsNullOrEmpty(updateUserInfoQuery.UserIdNo))
                    {
                        userinfo.UserIdNo = updateUserInfoQuery.UserIdNo;
                    }
                    if (!string.IsNullOrEmpty(updateUserInfoQuery.UserIdNoPhoto))
                    {
                        userinfo.UserIdNoPhoto = updateUserInfoQuery.UserIdNoPhoto;
                    }
                    if (!string.IsNullOrEmpty(updateUserInfoQuery.LoginName))
                    {
                        userinfo.LoginName = updateUserInfoQuery.LoginName;
                    }
                    if (!string.IsNullOrEmpty(updateUserInfoQuery.UserTel))
                    {
                        userinfo.UserTel = updateUserInfoQuery.UserTel;
                    }
                    if (!string.IsNullOrEmpty(updateUserInfoQuery.UserSex))
                    {
                        userinfo.UserSex = updateUserInfoQuery.UserSex;
                    }
                    if (updateUserInfoQuery.CompanyId != null)
                    {
                        userinfo.CompanyId = updateUserInfoQuery.CompanyId;
                    }
                    if (updateUserInfoQuery.States != null)
                    {
                        userinfo.States = (bool)updateUserInfoQuery.States;
                    }
                    if (updateUserInfoQuery.UserDateOfBirth != null)
                    {
                        userinfo.UserDateOfBirth = updateUserInfoQuery.UserDateOfBirth;
                    }
                    if (updateUserInfoQuery.RoleId != null)
                    {
                        userinfo.RoleId = updateUserInfoQuery.RoleId;
                    }
                    if (updateUserInfoQuery.PlatformId != null)
                    {
                        userinfo.PlatformId = updateUserInfoQuery.PlatformId;
                    }
                    if (!string.IsNullOrEmpty(updateUserInfoQuery.SelectCompany) && updateUserInfoQuery.SelectCompany.ToString().Equals("平台端"))
                    {
                        userinfo.CompanyId = null;
                    }
                    userinfo.UpdateTime = DateTime.Now;
                    userinfo.UpdateUserId = token.Id;
                    await _userinfoRepository.UpdateAsync(userinfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "更改成功！";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.SqlError;
                    baseResultDto.Message = "未获取到用户信息！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 批量/单个重置用户密码
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> ResetUserInfoPassword(ResetUserInfoPasswordQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.SqlError;
                int failnumber = 0;//更新失败数量
                string failid = "";//更新失败Id
                if (query.List != null && query.List.ToList().Count > 0)
                {
                    var idlist = query.List.ToList();
                    for (int i = 0; i < idlist.Count; i++)
                    {
                        var userinfo = await _userinfoRepository.FirstOrDefaultAsync(info => info.Id.ToString().Equals(idlist[i]));
                        if (userinfo != null)
                        {
                            userinfo.PassWord = CommonHelper.MD5Encryption("a123456", 32);
                            userinfo.UpdateTime = DateTime.Now;
                            userinfo.UpdateUserId = token.Id;
                            await _userinfoRepository.UpdateAsync(userinfo);
                            baseResultDto.IsSuccess = true;
                            baseResultDto.Code = HttpResultCode.Success;
                            baseResultDto.Message = "重置成功！";
                        }
                        else
                        {
                            failnumber++;
                            failid += string.IsNullOrEmpty(failid) ? idlist[i].ToString() : "," + idlist[i].ToString();
                            baseResultDto.Message = string.Format("一共更新{0}条，失败{1}条,失败id:{2}!", idlist.Count.ToString(), failid.ToString(), failid);
                        }
                    }
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "IDList不能为空！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 批量/单个用户信息状态更改
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> StatusChangeUserInfo(StatusChangeUserInfoQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.SqlError;
                int failnumber = 0;//更新失败数量
                string failid = "";//更新失败Id
                if (query.List != null && query.List.ToList().Count > 0)
                {
                    var idlist = query.List.ToList();
                    for (int i = 0; i < idlist.Count; i++)
                    {
                        var userinfo = await _userinfoRepository.FirstOrDefaultAsync(info => info.Id.ToString().Equals(idlist[i]));
                        if (userinfo != null)
                        {
                            userinfo.States = query.States;
                            userinfo.UpdateTime = DateTime.Now;
                            userinfo.UpdateUserId = token.Id;
                            await _userinfoRepository.UpdateAsync(userinfo);
                            baseResultDto.IsSuccess = true;
                            baseResultDto.Code = HttpResultCode.Success;
                            baseResultDto.Message = "更改成功！";
                        }
                        else
                        {
                            failnumber++;
                            failid += string.IsNullOrEmpty(failid) ? idlist[i].ToString() : "," + idlist[i].ToString();
                            baseResultDto.Message = string.Format("一共更新{0}条，失败{1}条,失败id:{2}!", idlist.Count.ToString(), failid.ToString(), failid);
                        }
                    }
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "IDList不能为空！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 验证手机号是否存在
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> VerificationUserTel(VerificationUserTelQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var userinfo = await _userinfoRepository.FirstOrDefaultAsync(info => info.UserTel == query.UserTel && info.IsDeleted == false);
                if (userinfo == null)
                {
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "手机号可用";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.SqlError;
                    baseResultDto.Message = "手机号已存在";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="token">token</param>
        /// <returns>ActionResult</returns>
        public async Task<ResultDto<bool>> Logout(string token)
        {
            if (!String.IsNullOrEmpty(token))
            {
                await this._redisRepository.DeleteAsync(new String[] { token });
            }

            var actionResult = new ResultDto<bool>();
            actionResult.Code = HttpResultCode.Success;
            actionResult.Message = "退出登录成功";
            actionResult.IsSuccess = true;
            actionResult.Data = true;
            return actionResult;
        }
    }
}
